﻿// WeinberyRecoveryServer.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include "mongoose.h"
#include "WdHttpServer.h"



static const char *s_listen_on = "http://0.0.0.0:8000";
static const char *s_web_directory = ".";

bool index(struct mg_connection* conn, void *request, void *func, std::string response)
{
    mg_http_reply(conn, 200, "", response.c_str());

    return true;
}

int main() 
{
    WdRouter router;
    WdHttpServer server;
    //
    router.Get("/", index);
    router.Post("/api/f", index);
    router.Put("/api/func/*", index);
    router.Delete("/api/delete/20210705", index);
    //
    return server.bind("http://0.0.0.0:8000").router(&router).run();
}


static void fn(struct mg_connection *c, int ev, void *ev_data, void *fn_data) 
{
  if (ev == MG_EV_ACCEPT && mg_url_is_ssl(s_listen_on)) 
  {
    // If s_listen_on URL is https://, tell listening connection to use TLS
    struct mg_tls_opts opts = {
        "ca.pem",         // Uncomment to enable two-way SSL
        "server.pem",     // Certificate PEM file
        "server.pem",  // This pem conains both cert and key
    };
    mg_tls_init(c, &opts);
  } 
  else if (ev == MG_EV_HTTP_MSG) 
  {
    struct mg_http_message *hm = (struct mg_http_message *) ev_data;
    printf("%s %s\n", std::string(hm->method.ptr,hm->method.len).c_str(), std::string(hm->uri.ptr, hm->uri.len).c_str());
    if (mg_http_match_uri(hm, "/api/f1"))
    {
      mg_http_reply(c, 200, "", "{\"result\": %d}\n", 123);  // Serve REST
    } 
    else if (mg_http_match_uri(hm, "/ws"))
    {
      // Upgrade to websocket. From now on, a connection is a full-duplex
      // Websocket connection, which will receive MG_EV_WS_MSG events.
      mg_ws_upgrade(c, hm, NULL);
    } 
    else if (mg_http_match_uri(hm, "/api/f2/*")) 
    {
      mg_http_reply(c, 200, "", "{\"result\": \"%.*s\"}\n", (int) hm->uri.len, hm->uri.ptr);
    } 
    else
    {
      struct mg_http_serve_opts opts = {s_web_directory, nullptr};
      mg_http_serve_dir(c, (struct mg_http_message *) ev_data, &opts);
    }
  } 
  else if (ev == MG_EV_WS_MSG) 
  {
      // Got websocket frame. Received data is wm->data. Echo it back!
      struct mg_ws_message *wm = (struct mg_ws_message *) ev_data;
      printf("ws flag: 0x%02x, data: %s\n", wm->flags, std::string(wm->data.ptr, wm->data.len).c_str());
      mg_ws_send(c, wm->data.ptr, wm->data.len, WEBSOCKET_OP_TEXT);
      mg_iobuf_delete(&c->recv, c->recv.len);
   }
  (void) fn_data;
}

int main1(void)
{
  struct mg_mgr mgr;                            // Event manager
  mg_log_set("2");                              // Set to 3 to enable debug
  mg_mgr_init(&mgr);                            // Initialise event manager
  mg_http_listen(&mgr, s_listen_on, fn, NULL);  // Create HTTP listener
  for (;;) mg_mgr_poll(&mgr, 1000);             // Infinite event loop
  mg_mgr_free(&mgr);
  return 0;
}
